﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
using System.Windows;
using System.Windows.Controls;
using SHomeWorkshop.LunarMind.Dialogs;
using System.Windows.Media.Imaging;
using System.Windows.Media;
using System.Windows.Documents;

namespace SHomeWorkshop.LunarMind.Commands
{
    /// <summary>
    /// 打印文档命令。此命令总是可以运行的。
    /// </summary>
    public static class PrintDocumentCommand
    {
        private static RoutedUICommand routedUICmd;//创建私有字段

        public static RoutedUICommand RoutedUICmd//创建只读静态属性
        {
            get { return routedUICmd; }
        }

        static PrintDocumentCommand()//类型构造器
        {
            routedUICmd = new RoutedUICommand(
                "PrintDocumentCommand",
                "PrintDocumentCommand",
                typeof(PrintDocumentCommand),//创建RoutedUICommand对象
                null/*new InputGestureCollection() 
                { 
                    new KeyGesture(Key.P,ModifierKeys.Control,"Ctrl+P")
                }*/);

            cmdBinding.Command = routedUICmd;
            cmdBinding.CanExecute += new CanExecuteRoutedEventHandler(cmdBinding_CanExecute);
            cmdBinding.Executed += new ExecutedRoutedEventHandler(cmdBinding_Executed);
        }

        private static CommandBinding cmdBinding = new CommandBinding();

        public static CommandBinding CmdBinding
        {
            get { return cmdBinding; }
        }

        static void cmdBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            PrintDocument();
        }

        internal static void PrintDocument()
        {
            System.Windows.Media.Imaging.RenderTargetBitmap rtb = new RenderTargetBitmap(
                    (int)(Globals.MainWindow.mainCanvas.ActualWidth * 3.125),
                    (int)(Globals.MainWindow.mainCanvas.ActualHeight * 3.125),
                    300, 300, PixelFormats.Pbgra32);//300÷96=3.125//用来打印的图片分辨率要高些。96DPI只适合屏幕显示。

            rtb.Render(Globals.MainWindow.mainCanvas);

            if (rtb == null)
            {
                MessageBox.Show("发生意外错误，未能获取当前文档的图形，无法继续打印！",
                    Globals.AppName, MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            Rect wholeRect = new Rect(0, 0, rtb.PixelWidth, rtb.PixelHeight);

            PaperInfo curPaperInfo = Globals.MainWindow.PageSetting;

            int width, height;
            if (Globals.MainWindow.PageDirection == Orientation.Horizontal)
            {
                width = curPaperInfo.LongSidePixcelCount;
                height = curPaperInfo.ShortSidePixcelCount;
            }
            else
            {
                height = curPaperInfo.LongSidePixcelCount;
                width = curPaperInfo.ShortSidePixcelCount;
            }

            //取出页面宽、高
            int paperWidth = width;
            int paperHeight = height;

            Thickness margin = new Thickness(0, 0, 0, 0);

            //Wpf是96DPI，而我要打印的图像是300DPI。3.25是比例值。
            width = (int)(width - margin.Left * 3.25 - margin.Right * 3.25);
            height = (int)(height - margin.Top * 3.25 - margin.Bottom * 3.25);

            PrintPreviewDialog pd = new PrintPreviewDialog() { Owner = Globals.MainWindow };

            pd.mainDocViewer.ShowPageBorders = true;

            int offcetX = 0, offcetY = 0;

            bool endX = false;
            bool endY = false;

            do
            {
                int realHeight;

                if (offcetY + height > wholeRect.Height)
                {
                    realHeight = (int)wholeRect.Height - offcetY;
                    endY = true;
                }
                else
                {
                    realHeight = height;
                }

                do
                {
                    int realWidth;

                    if (offcetX + width > wholeRect.Width)
                    {
                        realWidth = (int)wholeRect.Width - offcetX;
                        endX = true;
                    }
                    else
                    {
                        realWidth = width;
                    }

                    Int32Rect pieceRect;

                    if (width <= 0 || height <= 0) break;

                    pieceRect = new Int32Rect(offcetX, offcetY, realWidth, realHeight);
                    var array = new byte[realWidth * realHeight * rtb.Format.BitsPerPixel / 8];//每像素需要32位（4字节）。

                    rtb.CopyPixels(pieceRect, array, realWidth * rtb.Format.BitsPerPixel / 8, 0);

                    //跨度，每行像素数据的总字节数
                    //int stride = rtb.PixelWidth * rtb.Format.BitsPerPixel / 8;
                    //stride += 4 - stride % 4; //补上几个字节，使其可以被4整除 

                    var newBitmapImage = BitmapImage.Create(realWidth, realHeight, 300, 300,
                        PixelFormats.Pbgra32, null, array, realWidth * rtb.Format.BitsPerPixel / 8);

                    FixedPage fp = new FixedPage() { Width = paperWidth * 96 / 300, Height = paperHeight * 96 / 300 };
                    Image newImg = new Image() { Source = newBitmapImage };

                    Thickness realMargin = margin;

                    //if (masterEditor.PageSettingInfo.HorizontalCenter == true)
                    //{
                    //realMargin.Left = realMargin.Right = (paperWidth - realWidth) / 6.5;//6.5=3.25*2
                    //}

                    //if (masterEditor.PageSettingInfo.VerticalCenter == true)
                    //{
                    //realMargin.Top = realMargin.Bottom = (paperHeight - realHeight) / 6.5;
                    //}

                    newImg.Margin = realMargin;

                    fp.Children.Add(newImg);

                    pd.MainDoc.Pages.Add(
                        new System.Windows.Documents.PageContent()
                        {
                            Child = fp
                        });
                    offcetX += width;

                } while (offcetX <= wholeRect.Width && endX == false);

                offcetY += height;
                offcetX = 0; endX = false;
            } while (offcetY <= wholeRect.Height && endY == false);

            pd.ShowDialog();
        }

        static void cmdBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = true;//打印文档为分割图，此命令总是有效。
        }
    }
}
